import React, { memo, useEffect, useState } from "react"
import { Space, Table, Button } from "antd"
import {
	PlusCircleOutlined,
	EditOutlined,
	DeleteOutlined,
} from "@ant-design/icons"
const { Column } = Table
// 引入接口
import { reqPermissionMenuOrRolePermissionMenu } from "@/api/acl/permission"
// 引入ts类型
import type { MenuItem } from "@/api/acl/permission/type"
// 引入自定义Hooks
import { authPermission } from "@/hooks/directives"
interface DataType extends MenuItem {
	key: React.Key
}
// 整理数据函数
const arrangeData = (permissionList: MenuItem[]): DataType[] => {
	return permissionList.map((item: MenuItem) => {
		const { id, children } = item
		if (children && children.length === 0) {
			item.children = null
		}
		if (children && children.length > 0) {
			item.children = arrangeData(children)
		}
		return { ...item, key: id }
	})
}
const Permission: React.FC = () => {
	// 封装接口
	// 权限菜单列表
	const getPermission = async () => {
		try {
			let res = await reqPermissionMenuOrRolePermissionMenu(undefined)
			if (res.code === 200) {
				setPermissionList(arrangeData(res.data as MenuItem[]))
			}
		} catch (error) {
			console.log(error)
		} finally {
			console.log(111)
		}
	}

	// hooks
	const [permissionList, setPermissionList] = useState<DataType[]>([])

	useEffect(() => {
		getPermission()
	}, [])
	return (
		<Table
			dataSource={permissionList}
			bordered
			expandable={{ defaultExpandAllRows: true }}
		>
			<Column title="名称" dataIndex="name" key="name" width="25%" />
			<Column title="权限值" dataIndex="code" key="code" width="20%" />
			<Column
				title="更新时间"
				dataIndex="updateTime"
				key="updateTime"
				width="20%"
			/>
			<Column
				title="操作"
				key="action"
				width="35"
				render={(_, record: DataType) => (
					<Space size="middle">
						<Button
							style={authPermission("btn.Permission.add")}
							disabled={record.level === 4}
							icon={<PlusCircleOutlined />}
							type="primary"
						>
							{record.level === 3 ? "添加功能" : "添加菜单"}
						</Button>
						<Button
							style={authPermission("btn.Permission.update")}
							disabled={record.id === 1}
							icon={<EditOutlined />}
							type="primary"
						>
							编辑
						</Button>
						<Button
							style={authPermission("btn.Permission.remove")}
							disabled={record.id === 1}
							icon={<DeleteOutlined />}
							type="primary"
						>
							删除
						</Button>
					</Space>
				)}
			/>
		</Table>
	)
}
export default memo(Permission)
